package com.gton.config;

import com.gton.filter.LogInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * @description: SpringBoot-Web配置
 * @author: GuoTong
 * @createTime: 2021-10-05 15:37
 * @since JDK 1.8 OR 11
 **/
@Configuration
public class SpringBootConfig implements WebMvcConfigurer {

    @Autowired
    private LogInterceptor logInterceptor;

    /**
     * Description:  快捷Rest请求工具类
     * <p>
     * (1)@LoadBalanced可以使用eureka的服务名代替Ip端口去调用微服务||客户端
     * (2)新版本的移出了Ribbon的负载均衡的服务发现和选取策略，使用需依赖新版本的loadbalancer
     * (3)LoadBalanced注解既可以使用服务发现方式调用服务，又可以负载均衡
     *
     * @author: GuoTong
     * @date: 2022-09-20 19:10:11
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }


    /**
     * Description:  添加全局跨域CORS处理
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                .allowedOrigins("http://127.0.0.1:8080")
                // 是否允许证书
                .allowCredentials(true)
                // 设置允许的方法
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                // 设置允许的header属性
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(3600);
    }


    /**
     * Description: 静态资源过滤
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //ClassPath:/Static/** 静态资源释放
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        //释放swagger
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        //释放webjars
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * Description: 注册日志拦截器，全局流水号
     * @author: GuoTong
     * @date: 2022-10-18 22:17:25
     * @param registry
     * @return:void
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(logInterceptor)
                .addPathPatterns("/**");
    }

}
